package com.sz.mes.service.impl;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.diboot.core.util.BeanUtils;
import com.diboot.core.util.V;
import com.diboot.core.vo.JsonResult;
import com.sz.mes.entity.Goods;
import com.sz.mes.entity.Material;
import com.sz.mes.entity.TableHead;
import com.sz.mes.mapper.GoodsMapper;
import com.sz.mes.mapper.MaterialMapper;
import com.sz.mes.mapper.TableHeadMapper;
import com.sz.mes.service.GoodsService;
import com.sz.mes.service.impl.BaseCustomServiceImpl;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import java.util.*;

/**
 * 商品相关Service实现
 *
 * @author hem
 * @version 1.0
 * @date 2023-06-14
 * Copyright © szhs
 */
@Service
@Slf4j
public class GoodsServiceImpl extends BaseCustomServiceImpl<GoodsMapper, Goods> implements GoodsService {
    private final TableHeadMapper tableHeadMapper;
    private final GoodsMapper goodsMapper;

    public GoodsServiceImpl(TableHeadMapper tableHeadMapper, GoodsMapper goodsMapper) {
        this.tableHeadMapper = tableHeadMapper;
        this.goodsMapper = goodsMapper;
    }


    @Override
    public JsonResult insert(Goods entity) throws Exception{
        Goods goods = new Goods();
        goods.setExcelData(entity.getExcelData());
        try {
            if (goods.getExcelData() != null) {
                return dataProcess(goods.getExcelData(), goods.getId());
            }
        } catch (Exception e) {
            e.printStackTrace();
        }

        return JsonResult.OK("导入数据成功");
    }


    private JsonResult dataProcess(String excelData, Long id){
        //mapList 获取到所有的数据
        ArrayList<Map<String, String>> mapList = new ArrayList<>();


        //hashMap 表头对应的 序号
        HashMap<String, String> hashMap = new HashMap<>();
        //获取表头
        TableHead tableHead = tableHeadMapper.selectById(2);
        String data = tableHead.getData();
        JSONObject jsonObject = JSONObject.parseObject(data);
        for (Object map : jsonObject.entrySet()) {
//            hashMap.put(String.valueOf(((Map.Entry)map).getValue()),String.valueOf(((Map.Entry)map).getKey()));
            hashMap.put(String.valueOf(((Map.Entry) map).getKey()), String.valueOf(((Map.Entry) map).getValue()));
        }

        //获取完表头信息后清楚数据，给其他数据用
        mapList.clear();

        System.out.println("excelData:" + excelData);
        //json转为List
        JSONArray objects = JSONObject.parseArray(excelData);
//        JSONArray objects = JSONObject.parseArray(JSONObject.toJSONString(excelData));
        for (Object object : objects) {
            HashMap<String, String> map1 = JSONObject.parseObject(JSONObject.toJSONString(object), HashMap.class);
            mapList.add(map1);
        }

        System.out.println("mapList:" + mapList);

        for (Map map : mapList) {
            System.out.println(map);
            //物料表插入
            Goods goods = new Goods();
            goods.setGoodsCode((String) map.get(hashMap.get("料号")));
            goods.setGoodsName((String) map.get(hashMap.get("品名")));
            goods.setSpecifications((String) map.get(hashMap.get("规格")));
            goods.setUnit((String) map.get(hashMap.get("单位")));
            goods.setSaveCode((String) map.get(hashMap.get("存储编码")));
            goods.setSaveLocation((String) map.get(hashMap.get("存储地点")));
            goods.setFinanciaCode((String) map.get(hashMap.get("财务分类编码")));
            goods.setFinancialName((String) map.get(hashMap.get("财务分类名称")));
            goods.setShapeType((String) map.get(hashMap.get("形态属性")));
            goods.setProductCode((String) map.get(hashMap.get("生产部门编码")));
            goods.setProductGroupName((String) map.get(hashMap.get("生产部门名称")));
            goods.setCreateBy((String) map.get(hashMap.get("创建人")));
            /*Long materialQuantity = Long.valueOf((String) map.get(hashMap.get("物料数量")));
            if (materialQuantity != 0) {
                material.setMaterialQuantity(materialQuantity);
            } else {
                material.setMaterialQuantity(0L);
            }*/
//            goods.setExcelData(excelData);

//            try {
//                goodsMapper.insert(goods);
//            } catch (Exception e) {
//                throw e;
////                return JsonResult.FAIL_OPERATION("插入失败" + e.getMessage());
//            }
            Integer integer = goodsMapper.insertIgnoreInto(goods);
            System.out.println("integer = " + integer);

        }

        return JsonResult.OK("数据导入成功");
    }

    @Override
    public JsonResult selectGoodsId(String goodsCode) {
        QueryWrapper<Goods> goodsQueryWrapper = new QueryWrapper<>();
        goodsQueryWrapper.eq("goods_code", goodsCode);
        Goods goods = goodsMapper.selectOne(goodsQueryWrapper);
        if (goods != null){
            return JsonResult.OK(goods);
        }else {
            return JsonResult.FAIL_EXCEPTION("请检查物料，该物料不存在");
        }
    }

    @Override
    public JsonResult deleteById(Long id) {
        Integer deleteByGoodsId = goodsMapper.deleteByGoodsId(id);
        if (deleteByGoodsId > 0){
            return JsonResult.OK();
        }else {
            return JsonResult.FAIL_EXCEPTION("删除失败");
        }
    }

    //清空物料表
    @Override
    public void deleteAll() {
        goodsMapper.deleteAll();
    }

    @Override
    public List<String> filterDuplicateGoodsCode(List<String> goodsCodeList) {
        if (V.isEmpty(goodsCodeList)) {
            return Collections.emptyList();
        }
        List<String> goodsCodeLists = getValuesOfField(
                Wrappers.<Goods>lambdaQuery().in(Goods::getGoodsCode, goodsCodeList),
                Goods::getGoodsCode
        );
        return goodsCodeLists;
    }
}
